<script setup lang="ts">
import {
  NForm,
  NFormItem,
  NInput,
  NButton,
  NSteps,
  NStep,
  type DataTableColumns,
  NDataTable,
  NSelect,
  type UploadFileInfo,
  useMessage,
  NModal,
  type FormInst,
  // NPagination,
  NRadioGroup,
  NRadioButton,
  NScrollbar
} from 'naive-ui'
import { h, onMounted, reactive, ref, shallowRef, computed, watch } from 'vue'
import FixedAction from '@/components/FixedAction.vue'
import useRouteReplace from '@/hooks/useRouteReplace'
import { useRoute } from 'vue-router'
import type { IdentifyInfoModel, IdentifyFormModel, IdentifySubItemModel } from '@/api/batch'
import { sendRequest } from '@/utils/api'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import ModalCard from '@/components/ModalCard.vue'
import UploadFile from '@/views/common/UploadFile.vue'
import FileList from '@/components/FileList.vue'

const route = useRoute()
const routeReplace = useRouteReplace(route.query.redirect as string)
const isFromRecord = route.query.from === 'record'
const message = useMessage()

const validate = (form: FormInst | null): Promise<void> => {
  if (!form) return Promise.resolve()

  return new Promise((resolve, reject) => {
    form.validate((error) => {
      if (error) {
        reject()
      } else {
        resolve()
      }
    })
  })
}

const formData = ref({} as IdentifyFormModel)
const hzFormInst = shallowRef<FormInst | null>(null)
const submitLoading = ref(false)
const handleSubmit = async () => {
  if (submitLoading.value) return
  await Promise.all([validate(filesFormInst.value), validate(hzFormInst.value)])

  const files: Record<string, string> = {}
  filesFormData.forEach((e) => {
    files[e.key] = Array.from(e.value.values()).join(',')
  })

  try {
    submitLoading.value = true
    const [error, res] = await sendRequest<HttpResponse<IdentifyInfoModel>>({
      module: 'batch',
      api: 'identifyRegister',
      override: {
        data: {
          ...formData.value,
          ...files,
          identifyId: baseInfo.value.id
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    message.success(res.msg)
    window.flags.flushBatch = true
    routeReplace()
  } catch (error: any) {
    message.error(error.message)
  } finally {
    submitLoading.value = false
  }
}

const fileList = ref<UploadFileInfo[]>([])
const queryFileList = async () => {
  try {
    const [error, res] = await sendRequest<
      HttpResponse<
        {
          name: string
          path: string
          id: string
          type: string
        }[]
      >
    >({
      module: 'upload',
      api: 'list',
      override: {
        params: {
          ids: baseInfo.value.fileIds
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)

    fileList.value = res.data.map((e) => ({
      id: e.id,
      name: e.name,
      status: 'finished',
      url: e.path,
      type: e.type
    }))
  } catch (error) {
    console.log(error)
  }
}

const baseInfo = shallowRef({} as IdentifyInfoModel)
const isTF = ref(false)
const queryBaseInfo = async () => {
  try {
    const [error, res] = await sendRequest<HttpResponse<IdentifyInfoModel>>({
      module: 'batch',
      api: isFromRecord ? 'identifyDetailByIdentifyId' : 'identifyDetail',
      override: {
        params: isFromRecord
          ? { identifyId: route.params.id }
          : {
              batchId: route.params.id
            }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    if (res.data.identifyTime) {
      res.data.identifyTime = res.data.identifyTime.split(' ')[0]
    }
    baseInfo.value = res.data
    isTF.value = res.data.identifyTypeCode === 'A3101'

    if (isFromRecord) queryAttachments()
    queryFileList()
    queryTableData()
    queryDetailTableData()
  } catch (error) {
    console.log(error)
  }
}

const summaryBatchModalVisible = ref(false)
const summaryBatchModalLoading = ref(false)
const editTableIds = ref<number[]>([])
const summaryBatchModalFormInst = shallowRef<FormInst | null>(null)
const summaryBatchModalFormData = ref({
  authenticity: '',
  opinion: ''
})
const handleSummaryBatchModalSubmit = () => {
  summaryBatchModalFormInst.value?.validate(async (error) => {
    if (error) return
    try {
      summaryBatchModalLoading.value = true
      const [error, res] = await sendRequest<HttpResponse<IdentifySubItemModel>>({
        module: 'batch',
        api: 'summaryBatch',
        override: {
          data: {
            authenticity: summaryBatchModalFormData.value.authenticity,
            identifyId: baseInfo.value.id,
            opinion: summaryBatchModalFormData.value.opinion,
            subItemIds: editTableIds.value
          }
        }
      })
      if (error) throw error
      if (res.code !== 0) throw new Error(res.msg)
      message.success(res.msg)
      handleSummaryBatchModalClose()
      queryTableData()
    } catch (error: any) {
      message.error(error.message)
    } finally {
      summaryBatchModalLoading.value = false
    }
  })
}
const handleSummaryBatchModalClose = () => {
  summaryBatchModalVisible.value = false
  summaryBatchModalFormData.value = {
    authenticity: '',
    opinion: ''
  }
  summaryBatchModalFormInst.value?.restoreValidation()
}

const editTableRow = shallowRef<IdentifySubItemModel | null>(null)
const isEditCurrent = (row: IdentifySubItemModel) => editTableRow.value?.id === row.id
const summaryBatchLoading = ref(false)
const handleSummaryBatch = async () => {
  try {
    summaryBatchLoading.value = true
    if (!editTableRow.value) return
    const [error, res] = await sendRequest<HttpResponse<IdentifySubItemModel>>({
      module: 'batch',
      api: 'summaryBatch',
      override: {
        data: {
          authenticity: editTableRow.value.authenticity,
          identifyId: baseInfo.value.id,
          opinion: editTableRow.value.opinion,
          subItemIds: [editTableRow.value.id]
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    message.success(res.msg)
    editTableRow.value = null
    queryTableData()
  } catch (error: any) {
    message.error(error.message)
  } finally {
    summaryBatchLoading.value = false
  }
}

const tableData = ref<IdentifySubItemModel[]>([])
const tableLoading = ref(false)
// const paginationReactive = reactive({
//   page: 1,
//   pageSize: 10,
//   showSizePicker: true,
//   pageSizes: [10, 20, 50, 100, 500],
//   itemCount: 0,
//   onChange: (page: number) => {
//     paginationReactive.page = page
//     queryTableData()
//   },
//   onUpdatePageSize: (pageSize: number) => {
//     paginationReactive.pageSize = pageSize
//     paginationReactive.page = 1
//     queryTableData()
//   }
// })
const columns: DataTableColumns<IdentifySubItemModel> = [
  {
    type: 'selection'
  },
  {
    title: '序号',
    key: 'index',
    width: 80,
    align: 'center',
    render: (_, index) => index + 1
    // paginationReactive.pageSize * (paginationReactive.page - 1) + index + 1
  },
  {
    title: '征集品编码',
    key: 'subItemCode'
  },
  {
    title: '征集品名称',
    key: 'itemName'
  },
  {
    title: '类型',
    key: 'itemType'
  },
  {
    title: () => {
      return h('span', null, [
        h('span', { style: 'color: red; margin-right: 0.5em' }, '*'),
        h('span', null, '征集品真伪')
      ])
    },
    key: 'authenticity',
    render(e) {
      if (!isEditCurrent(e)) {
        if (e.authenticity === null) return null
        return e.authenticity === '0' ? '真' : e.authenticity === '1' ? '伪' : '无法确定'
      }
      return h(
        NSelect,
        // @ts-ignore
        {
          size: 'small',
          placeholder: '请选择',
          options: [
            { label: '真', value: '0' },
            { label: '伪', value: '1' },
            { label: '无法确定', value: '2' }
          ],
          value: e.authenticity,
          onUpdateValue: (value: string) => {
            e.authenticity = value as string
          }
        },
        null
      )
    }
  },
  {
    title: '意见',
    key: 'opinion',
    render(e) {
      if (!isEditCurrent(e)) return e.opinion
      return h(NInput, {
        size: 'small',
        placeholder: '请输入',
        value: e.opinion,
        onUpdateValue: (value) => {
          e.opinion = value as string
        }
      })
    }
  },
  {
    title: '操作',
    key: 'action',
    width: '200rem',
    align: 'center',
    fixed: 'right',
    render: (e) => {
      return editTableRow.value && isEditCurrent(e)
        ? [
            h(
              NButton,
              {
                color: '#6CB187',
                quaternary: true,
                size: 'small',
                style: 'margin-right: 10rem',
                loading: summaryBatchLoading.value,
                onClick: () => handleSummaryBatch()
              },
              { default: () => '确定' }
            ),
            h(
              NButton,
              {
                color: '#6CB187',
                quaternary: true,
                size: 'small',
                onClick: () => (editTableRow.value = null)
              },
              { default: () => '取消' }
            )
          ]
        : [
            h(
              NButton,
              {
                color: '#6CB187',
                quaternary: true,
                size: 'small',
                onClick: () => (editTableRow.value = e)
              },
              { default: () => '编辑' }
            )
          ]
    }
  }
]
const queryTableData = async () => {
  try {
    tableLoading.value = true
    const [error, res] = await sendRequest<HttpResponsePagination<IdentifySubItemModel>>({
      module: 'batch',
      api: 'identifySubItems',
      override: {
        params: {
          identifyId: baseInfo.value.id,
          limit: 10000000,
          page: 1
          // limit: paginationReactive.pageSize,
          // page: paginationReactive.page
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    tableData.value = res.data.list
    // paginationReactive.itemCount = res.data.totalCount
  } catch (error) {
    console.log(error)
  } finally {
    tableLoading.value = false
  }
}

const checkIds = ref<number[]>([])
const activeTableRow = ref<IdentifySubItemModel | null>()
const identifyBatchInfos = computed<IdentifySubItemModel[]>(() => {
  if (activeTableRow.value) return [activeTableRow.value]
  return detailTableData.value.filter((e) => checkIds.value.includes(e.id))
})
const identifyBatchFormInst = shallowRef<FormInst | null>(null)
const identifyBatchFormData = ref<any[]>([])
const identifyBatchModalVisible = ref(false)
const identifyBatchModalLoading = ref(false)

watch(identifyBatchModalVisible, (v) => {
  if (!v) activeTableRow.value = null
})

const setIdentifyBatchFormData = () => {
  identifyBatchFormData.value = exportModelList.value.map((e) => ({
    expertId: e.id,
    opinion: e.opinion,
    identifyValue: e.identifyValue,
    status: e.status
  }))
}
const handleIdentifyBatchModalSubmit = () => {
  identifyBatchFormInst.value?.validate(async (error) => {
    if (error) return
    try {
      identifyBatchModalLoading.value = true
      const [error, res] = await sendRequest<HttpResponse<IdentifySubItemModel>>({
        module: 'batch',
        api: 'identifyBatch',
        override: {
          data: {
            expertIdentifyList: identifyBatchFormData.value,
            identifyId: baseInfo.value.id,
            subItemIds: identifyBatchInfos.value.map((e) => e.id)
          }
        }
      })
      if (error) throw error
      if (res.code !== 0) throw new Error(res.msg)
      message.success(res.msg)
      handleIdentifyBatchModalClose()
      queryDetailTableData()
    } catch (error: any) {
      message.error(error.message)
    } finally {
      identifyBatchModalLoading.value = false
    }
  })
}
const handleIdentifyBatchModalOpen = () => {
  identifyBatchModalVisible.value = true
  queryExportModelList()
}
const handleIdentifyBatchModalClose = () => {
  identifyBatchModalVisible.value = false
  activeTableRow.value = null
  setIdentifyBatchFormData()
}

const detailTableData = ref<IdentifySubItemModel[]>([])
const detailTableLoading = ref(false)
// const detailPaginationReactive = reactive({
//   page: 1,
//   pageSize: 10,
//   showSizePicker: true,
//   pageSizes: [10, 20, 50, 100, 500],
//   itemCount: 0,
//   onChange: (page: number) => {
//     detailPaginationReactive.page = page
//     queryDetailTableData()
//   },
//   onUpdatePageSize: (pageSize: number) => {
//     detailPaginationReactive.pageSize = pageSize
//     detailPaginationReactive.page = 1
//     queryDetailTableData()
//   }
// })
const detailColumns: DataTableColumns<IdentifySubItemModel> = [
  {
    type: 'selection'
  },
  {
    title: '序号',
    key: 'index',
    width: 80,
    align: 'center',
    render: (_, index) => index + 1
    // detailPaginationReactive.pageSize * (detailPaginationReactive.page - 1) + index + 1
  },
  {
    title: '征集品编码',
    key: 'subItemCode'
  },
  {
    title: '征集品名称',
    key: 'itemName'
  },
  {
    title: '类型',
    key: 'itemType'
  },
  {
    title: '接收时间',
    key: 'receiveTime'
  },
  {
    title: '移交人',
    key: 'transferUser'
  },
  {
    title: '操作',
    key: 'action',
    width: '150rem',
    align: 'center',
    fixed: 'right',
    render: (e) => [
      h(
        NButton,
        {
          color: '#6CB187',
          quaternary: true,
          size: 'small',
          onClick: () => {
            activeTableRow.value = e
            queryExportModelList()
            identifyBatchModalVisible.value = true
          }
        },
        { default: () => '登记' }
      )
    ]
  }
]
const queryDetailTableData = async () => {
  try {
    detailTableLoading.value = true
    const [error, res] = await sendRequest<HttpResponsePagination<IdentifySubItemModel>>({
      module: 'batch',
      api: 'identifySubItems',
      override: {
        params: {
          identifyId: baseInfo.value.id,
          limit: 10000000,
          page: 1
          // limit: detailPaginationReactive.pageSize,
          // page: detailPaginationReactive.page
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    detailTableData.value = res.data.list
    // detailPaginationReactive.itemCount = res.data.totalCount
  } catch (error) {
    console.log(error)
  } finally {
    detailTableLoading.value = false
  }
}

const attachmentsLoading = ref(false)
const attachments = ref({} as any)
const queryAttachments = async () => {
  try {
    attachmentsLoading.value = true
    const [error, res] = await sendRequest<HttpResponse>({
      module: 'batch',
      api: 'identifyRegisterDetail',
      override: {
        params: {
          identifyId: baseInfo.value.id
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    attachments.value = res.data
    formData.value.totalOpinion = res.data.totalOpinion
    formData.value.remark = res.data.remark
    filesFormData.forEach((e) => {
      const files = res.data[e.key.replace('Ids', 's')]
      if (!files) return
      e.defaultValue = files.map((e: any) => ({
        id: e.id,
        name: e.name,
        status: 'finished',
        url: e.path
      }))

      e.value = new Map(files.map((e: any) => [e.id, e.id]))
    })
  } catch (error) {
    console.error(error)
  } finally {
    attachmentsLoading.value = false
  }
}

const filesFormInst = shallowRef<FormInst | null>(null)
const filesFormData = reactive<
  {
    label: string
    key: string
    required?: boolean
    value: Map<string, string>
    defaultValue?: UploadFileInfo[]
  }[]
>([
  {
    label: '鉴定方案',
    key: 'planFileIds',
    value: new Map(),
    required: true
  },
  {
    label: '专家鉴定意见',
    key: 'expertFileIds',
    value: new Map(),
    required: true
  },
  {
    label: '汇总鉴定意见',
    key: 'summaryResultFileIds',
    value: new Map(),
    required: true
  },
  {
    label: '会议汇报材料',
    key: 'meetingResultFileIds',
    value: new Map(),
    required: true
  },
  {
    label: '会议纪要材料',
    key: 'meetingMinutesFileIds',
    value: new Map(),
    required: true
  },
  {
    label: '合同和发票材料',
    key: 'contractFileIds',
    value: new Map()
  },
  {
    label: '视频材料',
    key: 'videoFileIds',
    value: new Map()
  },
  {
    label: '音频材料',
    key: 'audioFileIds',
    value: new Map()
  },
  {
    label: '其他材料',
    key: 'otherFileIds',
    value: new Map()
  },
  {
    label: '价格结果材料',
    key: 'priceFileIds',
    value: new Map(),
    required: true
  },
  {
    label: '谈判会材料',
    key: 'talkFileIds',
    value: new Map(),
    required: true
  }
])
const handleUploadFinish = (key: string, e: any) => {
  const target = filesFormData.find((e) => e.key === key)
  if (!target) return
  target.value.set(e.id, e.data.fileId)

  if (!target.required) return
  filesFormInst.value?.validate(
    () => {},
    (rule) => {
      return rule?.key === key
    }
  )
}
const handleUploadRemove = (key: string, id: string) => {
  const target = filesFormData.find((e) => e.key === key)
  if (!target) return
  target.value.delete(id)

  if (!target.required) return
  filesFormInst.value?.validate(
    () => {},
    (rule) => {
      return rule?.key === key
    }
  )
}
const validatorFile = (_: string, value: Map<string, string>) => {
  if (!value.size) {
    return new Error('请上传该附件')
  }
  return true
}

const expertList = ref<any[]>([])
const expertLoading = ref(false)
const queryExpertLIst = async () => {
  try {
    expertLoading.value = true
    const [error, res] = await sendRequest<HttpResponse<any[]>>({
      module: 'batch',
      api: 'expertList',
      override: {
        params: {
          identifyId: baseInfo.value.id
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    expertList.value = res.data
  } catch (error) {
    console.error(error)
  } finally {
    expertLoading.value = false
  }
}

const exportModelList = ref<any[]>([])
const exportModelLoading = ref(false)
const queryExportModelList = async () => {
  try {
    exportModelLoading.value = true
    const [error, res] = await sendRequest<HttpResponse<any[]>>({
      module: 'batch',
      api: 'expertList',
      override: {
        params: {
          identifyId: baseInfo.value.id,
          subItemId: activeTableRow.value?.id
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    exportModelList.value = res.data
    setIdentifyBatchFormData()
  } catch (error) {
    console.error(error)
  } finally {
    exportModelLoading.value = false
  }
}

onMounted(() => {
  Promise.allSettled([queryBaseInfo(), queryExpertLIst()])
})
</script>

<template>
  <div class="register-tf">
    <div class="rtf-card rtf-steps">
      <NSteps v-if="!isFromRecord">
        <NStep title="汇总登记" />
        <NStep title="物品登记" />
      </NSteps>
      <NSteps v-else>
        <NStep title="编辑" />
        <NStep title="部分负责人" />
      </NSteps>
    </div>

    <div class="br"></div>

    <div class="rtf-title">基本信息</div>
    <NForm
      disabled
      label-placement="left"
      label-width="100rem"
      class="rtf-card grid"
    >
      <NFormItem label="鉴定编号：">
        <NInput
          placeholder="/"
          :value="baseInfo.identifyCode"
        />
      </NFormItem>
      <NFormItem label="鉴定名称：">
        <NInput
          placeholder="/"
          :value="baseInfo.identifyName"
        />
      </NFormItem>
      <NFormItem label="鉴定日期：">
        <NInput
          placeholder="/"
          :value="baseInfo.identifyTime"
        />
      </NFormItem>
      <NFormItem label="鉴定地点：">
        <NInput
          placeholder="/"
          :value="baseInfo.identifyAddress"
        />
      </NFormItem>
      <NFormItem label="鉴定类型：">
        <NInput
          placeholder="/"
          :value="baseInfo.identifyType"
        />
      </NFormItem>
      <NFormItem label="鉴定专家：">
        <NSelect
          :options="expertList"
          :loading="expertLoading"
          :value="baseInfo.identifyExpertIds?.split(',')"
          multiple
          label-field="userName"
          value-field="id"
          placeholder="/"
        />
      </NFormItem>
      <NFormItem label="描述：">
        <NInput
          placeholder="/"
          type="textarea"
          rows="1"
          :value="baseInfo.identifyDescription"
        />
      </NFormItem>
      <NFormItem label="附件：">
        <FileList :fileList="fileList" />
      </NFormItem>
    </NForm>

    <template v-if="isTF">
      <div class="br"></div>

      <div class="rtf-title">汇总结果</div>
      <NForm
        ref="hzFormInst"
        :model="formData"
        label-placement="left"
        label-width="130rem"
        require-mark-placement="left"
        inline
        class="rtf-card grid"
      >
        <NFormItem
          label="鉴定汇总意见："
          path="totalOpinion"
          :rule="{ required: true, message: '鉴定汇总意见必填，请输入', trigger: 'blur' }"
        >
          <NInput
            placeholder="请输入"
            v-model:value="formData.totalOpinion"
          />
        </NFormItem>
        <NFormItem label="备注：">
          <NInput
            placeholder="请输入"
            type="textarea"
            rows="1"
            v-model:value="formData.remark"
          />
        </NFormItem>
        <NFormItem style="justify-self: end">
          <NButton
            color="#5FB17F"
            ghost
            :disabled="editTableIds.length === 0"
            @click="summaryBatchModalVisible = true"
          >
            批量登记
          </NButton>
        </NFormItem>
      </NForm>
      <NDataTable
        :loading="tableLoading"
        :data="tableData"
        :columns="columns"
        :row-key="(row) => row.id"
        @update-checked-row-keys="($event) => (editTableIds = ($event as number[]))"
        max-height="200rem"
        class="rtf-card"
      />
      <!-- <NPagination
        class="rtf-card"
        style="padding-top: 0"
        show-size-picker
        show-quick-jumper
        :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize"
      >
        <template #suffix>页</template>
      </NPagination> -->

      <NModal
        :auto-focus="false"
        v-model:show="summaryBatchModalVisible"
      >
        <ModalCard
          @submit="handleSummaryBatchModalSubmit"
          @close="handleSummaryBatchModalClose"
          :loading="summaryBatchModalLoading"
          action
          title="登记"
        >
          <div class="sbmc-wrapper">
            <NForm
              ref="summaryBatchModalFormInst"
              class="sbmc"
              label-placement="left"
              require-mark-placement="left"
              label-width="100rem"
              :model="summaryBatchModalFormData"
            >
              <NFormItem
                label="征集品真伪"
                path="authenticity"
                :rule="{ required: true, message: '征集品真伪必填，请选择' }"
              >
                <NSelect
                  v-model:value="summaryBatchModalFormData.authenticity"
                  placeholder="请选择"
                  :options="[
                    { label: '真', value: '0' },
                    { label: '伪', value: '1' },
                    { label: '无法确定', value: '2' }
                  ]"
                />
              </NFormItem>
              <NFormItem label="意见">
                <NInput
                  v-model:value="summaryBatchModalFormData.opinion"
                  placeholder="请输入"
                  type="textarea"
                  rows="5"
                />
              </NFormItem>
            </NForm>
          </div>
        </ModalCard>
      </NModal>
    </template>

    <div class="br"></div>

    <div class="rtf-title">
      <span>鉴定清单</span>
      <NButton
        color="#5FB17F"
        ghost
        style="display: flex"
        :disabled="!checkIds.length"
        @click="handleIdentifyBatchModalOpen"
      >
        批量登记
      </NButton>
    </div>

    <NDataTable
      :loading="detailTableLoading"
      :data="detailTableData"
      :columns="detailColumns"
      :row-key="(row) => row.id"
      @update-checked-row-keys="($event) => (checkIds = ($event as number[]))"
      max-height="200rem"
      class="rtf-card"
    />
    <!-- <NPagination
      class="rtf-card"
      style="padding-top: 0"
      show-size-picker
      show-quick-jumper
      :page-sizes="detailPaginationReactive.pageSizes"
      :item-count="detailPaginationReactive.itemCount"
      :page="detailPaginationReactive.page"
      :page-size="detailPaginationReactive.pageSize"
      @update:page="detailPaginationReactive.onChange"
      @update:page-size="detailPaginationReactive.onUpdatePageSize"
    >
      <template #suffix>页</template>
    </NPagination> -->
    <NModal
      v-model:show="identifyBatchModalVisible"
      :auto-focus="false"
    >
      <ModalCard
        @submit="handleIdentifyBatchModalSubmit"
        @close="handleIdentifyBatchModalClose"
        :loading="identifyBatchModalLoading"
        action
        title="登记"
        title-style="padding-bottom: 10rem"
      >
        <NScrollbar style="max-height: 80vh">
          <div class="sbmc-wrapper">
            <span class="rtf-title-global">物品信息</span>
            <NForm
              class="sbmc grid"
              label-placement="left"
              :show-feedback="false"
            >
              <template
                v-for="(item, i) in identifyBatchInfos"
                :key="i"
              >
                <NFormItem label="征集品编码：">
                  <NInput
                    disabled
                    placeholder="/"
                    :value="item.subItemCode"
                    style="min-width: 200rem"
                  />
                </NFormItem>
                <NFormItem label="征集品名称：">
                  <NInput
                    disabled
                    placeholder="/"
                    :value="item.itemName"
                  />
                </NFormItem>
                <NFormItem label="类型：">
                  <NInput
                    disabled
                    placeholder="/"
                    :value="item.itemType"
                  />
                </NFormItem>
              </template>
            </NForm>

            <div class="br-global"></div>

            <span class="rtf-title-global">鉴定结果</span>

            <NForm
              ref="identifyBatchFormInst"
              class="sbmc grid"
              label-placement="left"
              require-mark-placement="left"
              label-width="100rem"
              :model="identifyBatchFormData"
            >
              <template
                v-for="(item, i) in identifyBatchFormData"
                :key="item.expertId"
              >
                <NFormItem label="鉴定专家：">
                  <NSelect
                    :options="exportModelList"
                    :loading="exportModelLoading"
                    disabled
                    placeholder="/"
                    label-field="userName"
                    value-field="id"
                    :value="item.expertId"
                  />
                </NFormItem>
                <NFormItem
                  v-if="isTF"
                  label="物品真伪："
                  :path="`${i}[status]`"
                  :rule="{
                    required: true,
                    message: '物品真伪必填，请选择',
                    type: 'number',
                    trigger: ['change', 'blur']
                  }"
                >
                  <NRadioGroup v-model:value="item.status">
                    <NRadioButton :value="0">真</NRadioButton>
                    <NRadioButton :value="1">伪</NRadioButton>
                    <NRadioButton :value="2">无法确定</NRadioButton>
                  </NRadioGroup>
                </NFormItem>
                <NFormItem
                  v-else
                  label="价格评估："
                  :path="`${i}[identifyValue]`"
                  :rule="{
                    required: true,
                    message: '价格评估必填，请输入',
                    trigger: 'blur'
                  }"
                >
                  <NInput
                    placeholder="请输入"
                    v-model:value="item.identifyValue"
                  />
                </NFormItem>
                <NFormItem label="意见：">
                  <NInput
                    type="textarea"
                    rows="1"
                    placeholder="请输入"
                    v-model:value="item.opinion"
                  />
                </NFormItem>
              </template>
            </NForm>
          </div>
        </NScrollbar>
      </ModalCard>
    </NModal>

    <div class="br"></div>

    <div class="rtf-title">附件</div>
    <NForm
      ref="filesFormInst"
      :model="filesFormData"
      class="rtf-card attachment-grid"
      require-mark-placement="left"
      label-placement="left"
    >
      <div
        v-for="(item, i) in filesFormData"
        :key="i"
        class="attachment"
      >
        <div class="attachment-title">{{ item.label }}</div>
        <NFormItem
          label="附件："
          :path="`${i}[value]`"
          :rule="
            item.required
              ? {
                  required: true,
                  key: item.key,
                  validator: () => validatorFile(item.key, item.value)
                }
              : undefined
          "
        >
          <!--     v-if="!isFromRecord || (isFromRecord && item.defaultValue)" -->
          <UploadFile
            v-if="!isFromRecord || (isFromRecord && !attachmentsLoading)"
            :max="10"
            :default-file-list="item.defaultValue"
            multiple
            @finish="(e) => handleUploadFinish(item.key, e)"
            @remove="(e) => handleUploadRemove(item.key, e)"
          >
            <template #trigger="{ handleClick }">
              <n-button
                @click="handleClick"
                color="#6CB187"
                ghost
                size="small"
              >
                点击上传
              </n-button>
            </template>
          </UploadFile>
        </NFormItem>
      </div>
    </NForm>
  </div>

  <FixedAction>
    <div class="register-tf-buttons">
      <NButton
        color="#999999"
        ghost
        :disabled="submitLoading"
        @click="routeReplace"
      >
        取消
      </NButton>

      <NButton
        color="#5FB17F"
        :disabled="submitLoading"
        :loading="submitLoading"
        @click="handleSubmit"
      >
        确定
      </NButton>
    </div>
  </FixedAction>
</template>

<style lang="scss">
.br-global {
  position: relative;
  width: 100%;
  padding: 30rem 0;

  &::after {
    content: '';
    position: absolute;
    width: 100%;
    top: 50%;
    left: 0;
    border-top: 1px dotted #bc9e70;
    transform: translateY(-50%);
  }
}
</style>
<style scoped lang="scss">
.register-tf {
  min-height: 100%;
  padding: 15rem 0 110rem;
  background-color: #f0efee;

  :deep(.n-data-table__pagination) {
    justify-content: flex-start;
  }

  .br {
    position: relative;
    width: 100%;
    padding: 30rem 0;

    &::after {
      content: '';
      position: absolute;
      width: 100%;
      top: 50%;
      left: 0;
      border-top: 1px dotted #bc9e70;
      transform: translateY(-50%);
    }
  }

  .rtf-card {
    padding: 20rem;
    background-color: #e1e1e1;
  }

  .n-form.grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 0 60rem;
    padding-bottom: 0;
  }

  .n-form.attachment-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10rem 15rem;
    padding: 20rem 30rem;

    .attachment {
      &-title {
        margin-bottom: 0.5em;
        font-weight: 600;
        font-size: 16rem;
      }

      .n-form-item {
        margin-left: 2em;
      }
    }
  }

  .rtf-title,
  :global(.rtf-title-global) {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    font-size: 26rem;
    margin-bottom: 30rem;
    color: #048c5e;
    line-height: 1;
  }

  :global(.rtf-title-global) {
    font-size: 16rem;
    margin-bottom: 12rem;
  }

  .rtf-steps {
    padding: 20rem 50% 20rem 20rem;
    margin-top: 15rem;
  }
}

.register-tf-buttons {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0 16rem;

  .n-button {
    width: 100rem;
    height: 50rem;
  }
}

.sbmc-wrapper {
  min-width: 600rem;
  padding: 30rem 44rem 0;
}
.sbmc {
  padding: 30rem 35rem 30rem;
  background-color: #ebeceb;

  &.grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 0 30rem;
  }
}
</style>
